package com.bilibili.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import com.bilibili.entity.User;
import com.bilibili.service.UserService;
import com.bilibili.service.impl.UserServiceImpl;

@WebServlet("/login.do")
public class loginServlet extends HttpServlet {
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
   	        // 设置响应头，允许跨域和携带凭证
    	        // 关键：设置为前端实际运行的 origin（如 http://localhost:5500）
    	        response.setHeader("Access-Control-Allow-Origin", "http://localhost:5500"); 
    	        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    	        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    	        response.setHeader("Access-Control-Allow-Credentials", "true"); // 允许带 Cookie
    	        
    	        // 其他逻辑不变...
    	    
    	        
    	        PrintWriter out = response.getWriter();
    	        JSONObject jsonResponse = new JSONObject();
    	        
    	        try {
    	            String username = request.getParameter("username");
    	            String password = request.getParameter("password");
    	            
    	            // 记录调试信息
    	            System.out.println("用户尝试登录: " + username);
    	            
    	            // 处理自动保存功能
    	            String autoSave = request.getParameter("autoSave");
    	            if("on".equals(autoSave)){
    	                Cookie cookie = new Cookie("uname", username);
    	                Cookie cookie2 = new Cookie("upwd", password);
    	                cookie.setMaxAge(60*60*24*7);
    	                cookie2.setMaxAge(60*60*24*7);
    	                cookie.setPath("/"); // 设置路径
    	                cookie2.setPath("/");
    	                // cookie.setDomain("localhost"); // 开发环境通常不需要设置
    	                response.addCookie(cookie);
    	                response.addCookie(cookie2);
    	            } else {
    	                // 清除 cookie
    	                Cookie cookie = new Cookie("uname", "");
    	                Cookie cookie2 = new Cookie("upwd", "");
    	                cookie.setMaxAge(0);
    	                cookie2.setMaxAge(0);
    	                cookie.setPath("/");
    	                cookie2.setPath("/");
    	                response.addCookie(cookie);
    	                response.addCookie(cookie2);
    	            }
    	            
    	            UserService us = new UserServiceImpl();
    	            Map<String, Object> map = us.userLogin(username, password);
    	            
    	            
    	            // 记录调试信息
    	            System.out.println("登录结果: " + map);
    	            
    	            if(map.get("loginUser") != null) {
    	            	// 从map中获取已登录的用户对象
    	                User loginUser = (User) map.get("loginUser");
    	                
    	            	Map<String, Object> userData = new HashMap<>();
        	            userData.put("userId", loginUser.getUserId());
        	            userData.put("username", loginUser.getUsername());
        	            userData.put("avatarUrl", loginUser.getAvatarUrl());
        	            
    	                HttpSession session = request.getSession(true); // 确保创建新会话
    	                session.setAttribute("loginUser", map.get("loginUser"));
    	                userData.put("avatarUrl", loginUser.getAvatarUrl());
    	                jsonResponse.put("data", userData);
    	                jsonResponse.put("success", true);
    	                jsonResponse.put("message", "登录成功");
    	                jsonResponse.put("data", userData); // 添加用户数据到响应
    	                	
    	            } else {
    	                jsonResponse.put("success", false);
    	                jsonResponse.put("message", map.get("msg") != null ? 
    	                    map.get("msg").toString() : "用户名或密码错误");
    	            }
    	            
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            System.err.println("登录过程发生错误: " + e.getMessage());
    	            jsonResponse.put("success", false);
    	            jsonResponse.put("message", "登录过程发生错误: " + e.getMessage());
    	        }
    	        
    	        out.print(jsonResponse.toString());
    	        out.flush();
    	    }
    	    
    	    // 处理预检请求
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:5500");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setStatus(HttpServletResponse.SC_OK);
    }
    	}